/**
 * 存储localStorage
 */
export const setCookieStorage = (name, content) => {
  if (!name) return
  if (typeof content === 'string') {
    window.localStorage.setItem(name, content)
  } else {
    window.localStorage.setItem(name, JSON.stringify(content))
  }
}
/**
 * 获取localStorage
 */
export const getCookieStorage = name => {
  if (!name) return
  var str = window.localStorage.getItem(name)
  if (str === null) return // 如果取的本地存储没有存入的情况下 取到的本地存储为null
  if (str.indexOf('{') !== -1 || str.indexOf('[') !== -1) {
    return JSON.parse(str)
  } else {
    return str
  }
}
/**
 * 全部清除localStorage
 */
export const clearCookieStorage = () => {
  window.localStorage.clear()
}
/**
 * 删除localStorage
 */
export const removeCookieStorage = name => {
  if (!name) return
  window.localStorage.removeItem(name)
}

/**
 * 存cookie
 */
export const setCookie = (cname, value, expiredays) => {
  var exdate = new Date()
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = cname + '=' + escape(value) +
  ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString())
}

/**
 * 取cookie
 */
export const getCookie = (cname) => {
  if (document.cookie.length > 0) {
    var cstart = document.cookie.indexOf(cname + '=')
    var cend
    if (cstart !== -1) {
      cstart = cstart + cname.length + 1
      cend = document.cookie.indexOf(';', cstart)
      if (cend === -1) cend = document.cookie.length
      return unescape(document.cookie.substring(cstart, cend))
    }
  }
  return ''
}
/**
 * 添加删除class
 */
export const addClass = (target, className) => {
  let classList = Array.prototype.slice.call(target.classList)
  if (isSet(classList, className)) {
    console.log('存在active类')
    return false
  } else {
    target.classList.add('active')
  }
}
export const removeClass = (target, className) => {
  let classList = target.classList
  classList.remove('active')
}

/*
 * 检查元素类型
*/
export const whatType = item => {
  return Object.prototype.toString.call(item).slice(8, -1).toLowerCase()
}

/*
 * 修改时间格式
 * input： 2020-7-3 15:11:48
 * output： 2020/7/3
*/
export const changeDate = item => {
  return item.split(' ')[0].replace(/-/g, '/')
}

/*
 * 隐藏手机号码中间四位
 * input： 12344448888
 * output： 123****8888
*/
export const hideNum = item => {
  if (item.length === 11) {
    return item.substr(0, 3) + '****' + item.substr(-4, 4)
  }
}

/*
 * 获取周几
 * input： number 0-6
 * output： 周一...周日
*/
export const getWeekday = item => {
  switch (item) {
    case 0:
      return '周日'
    case 1:
      return '周一'
    case 2:
      return '周二'
    case 3:
      return '周三'
    case 4:
      return '周四'
    case 5:
      return '周五'
    case 6:
      return '周六'
    default:
      return ''
  }
}

/*
 * 判断对象中是否存在某一已知元素
*/
export const isSet = (obj, item) => {
  if (arguments.length !== 2) return
  if (whatType(obj) === 'object' || whatType(obj) === 'string' || whatType(obj) === 'array') {
    obj = Array.prototype.slice.call(obj)
    for (let k in obj) {
      if (obj[k] === item) {
        return true
      } else {
        return false
      }
    }
  }
}

/*
 * 取一个list中的一个元素
 * input: [{id:'1',name:'2'},{id:'11',name:'22'},{id:'111',name:'222'}] , id , 1
 * output: {id:'1',name:'2'}
*/
export const getOneOfList = (obj, item, value) => {
  for (var i in obj) {
    if (obj[i][item] === value) {
      return obj[i]
    }
  }
  return null
}
/**
 * 改变时间样式
 * 传参格式 Mon Jan 01 2018 00:00:00 GMT+0800 (中国标准时间)
 * 返回类型 2018-01-01
 */
export const getFormateDate = (time, fmt) => {
  if (Object.prototype.toString.call(time) !== '[object Date]') return
  let o = {
    'y+': time.getFullYear(),
    'M+': time.getMonth() + 1,
    'd+': time.getDate(),
    'h+': time.getHours(),
    'm+': time.getMinutes(),
    's+': time.getSeconds(),
    'q+': Math.floor((time.getMonth() + 3) / 3),
    'S': time.getMilliseconds()
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, o[k].toString().length === 1 ? ('0' + o[k]) : o[k])
    }
  }
  return fmt
}
/**
 * 获取当前日期的0点0分0秒和23点59分59秒
 */
export const getTodays = () => {
  let current = new Date()
  let currentDateArr = getFormateDate(current, 'hh-mm-ss-S').split('-')
  // 获取此时此刻距离凌晨0点的毫秒数
  let getMilliseconds = (currentDateArr[0] * 60 * 60 + currentDateArr[1] * 60 + Number(currentDateArr[2])) * 1000 + Number(currentDateArr[3])
  let oneday = (23 * 60 * 60 + 59 * 60 + 59) * 1000 + 999
  let todayFirst = new Date(current.getTime() - getMilliseconds)
  let todayLast = new Date(current.getTime() - getMilliseconds + oneday)
  return [todayFirst, todayLast]
}
/**
 * 获取style样式
 */
export const getStyle = (element, attr, NumberMode = 'int') => {
  let target
  // scrollTop 获取方式不同，没有它不属于style，而且只有document.body才能用
  if (attr === 'scrollTop') {
    target = element.scrollTop
  } else if (element.currentStyle) {
    target = element.currentStyle[attr]
  } else {
    target = document.defaultView.getComputedStyle(element, null)[attr]
  }
  return NumberMode === 'float' ? parseFloat(target) : parseInt(target)
}
/**
 * 页面到达底部，加载更多
 */
export const loadMore = (element, callback) => {
  let windowHeight = window.screen.height
  let height
  let setTop
  let paddingBottom
  let marginBottom
  let requestFram
  let oldScrollTop
  document.body.addEventListener('scroll', () => {
    loadMore()
  }, false)
  element.addEventListener('touchstart', () => {
    height = element.offsetHeight
    setTop = element.offsetTop
    paddingBottom = getStyle(element, 'paddingBottom')
    marginBottom = getStyle(element, 'marginBottom')
  }, { passive: true })
  element.addEventListener('touchmove', () => {
    loadMore()
  }, { passive: true })
  element.addEventListener('touchend', () => {
    oldScrollTop = document.body.scrollTop
    moveEnd()
  }, { passive: true })
  const moveEnd = () => {
    requestFram = requestAnimationFrame(() => {
      if (document.body.scrollTop !== oldScrollTop) {
        oldScrollTop = document.body.scrollTop
        loadMore()
        moveEnd()
      } else {
        cancelAnimationFrame(requestFram)
        height = element.offsetHeight
        loadMore()
      }
    })
  }
  const loadMore = () => {
    if (document.body.scrollTop + windowHeight >= height + setTop + paddingBottom + marginBottom) {
      callback()
    }
  }
}
